<?php

/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 */

require_once ('data/api/IDictionary.php');

/**
 * Configuration
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @package Simplify_Kernel
 */
class Config implements IDictionary
{

  /**
   * Config Data.
   *
   * @var array
   */
  protected $data;

  /**
   *
   * @var Config
   */
  protected $parent;

  /**
   * Constructor.
   *
   * @param mixed $data initial data
   * @param $except
   * @param $filter
   * @return unknown_type
   */
  public function __construct($data = null, Config $parent = null)
  {
    $this->parent = $parent;
    $this->reset($data);
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/data/IDictionary#copyAll($data, $except, $filter)
   */
  public function copyAll($data)
  {
    if ($data instanceof IDictionary) {
      $data = $data->getAll();
    }

    else {
      $data = ( array ) $data;
    }

    foreach ($data as $name => $value) {
      $this->set($name, $value);
    }

    return $this;
  }

  /**
   * Load, parse and copy all data from YAML file.
   *
   * @param string $file full path to yaml file
   * @return Config
   */
  public function copyAllFromYAMLFile($file)
  {
    $file = $this->resolveReferences($file);

    if (! file_exists($file)) {
      throw new ConfigurationException("Could not load config file <b>$file</b>: file not found");
    }

    $data = Syml::read($file);

    return $this->copyAll($data);
  }

  /**
   * Parse and copy all data from YAML string.
   *
   * @param string $yaml yaml string
   * @return Config
   */
  public function copyAllFromYAML($yaml)
  {
    $data = Syml::load($yaml);

    return $this->copyAll($data);
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/data/IDictionary#del($name)
   */
  public function del($name)
  {
    extract($this->parsePath($name));

    if ($sub !== false) {
      return $this->get($name)->del($sub);
    }

    elseif ($this->has($name)) {
      unset($data[$name]);

      return $this;
    }

    throw new Exception("Could not delete <b>$name</b>: path not found");
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/data/IDictionary#get($name, $default, $filter)
   */
  public function get($name)
  {
    $args = func_get_args();
    $default = sy_get_param($args, 1);
    $filter = sy_get_param($args, 2);

    if ($this->has($name, $default, $filter)) {
      extract($this->parsePath($name));

      if ($name == '.') {
        return $sub ? $this->root()->get($name, $default, $filter)->get($sub, $default, $filter) : $this->root();
      }

      elseif ($name == '..') {
        return $sub ? $this->up()->get($name, $default, $filter)->get($sub, $default, $filter) : $this->up();
      }

      elseif ($sub !== false) {
        return $this->get($name, $default, $filter)->get($sub, $default, $filter);
      }

      else {
        return $this->data[$name];
      }
    }

    return $this->resolveReferences($default);
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/data/IDictionary#getAll()
   */
  public function getAll()
  {
    $data = array();

    foreach ($this->data as $name => $value) {
      if ($value instanceof IDictionary) {
        $data[$name] = $value->getAll();
      }
      else {
        $data[$name] = $value;
      }
    }

    return $data;
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/data/api/IDictionary#getNames()
   */
  public function getNames()
  {
    return array_keys($this->data);
  }

  /**
   * Parse path info from $name.
   *
   * @param string $name the path
   * @return array
   */
  protected function parsePath($name)
  {
    $_name = $name;
    $path = explode(':', $name);
    $name = $this->resolveReferences($path[0]);

    $sub = ($p = strpos($_name, ':')) > 1 ? substr($_name, $p + 1) : false;

    return array(
      'path' => $path, 'name' => $name, 'sub' => $sub
    );
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/data/IDictionary#has($name, $filter)
   */
  public function has($name)
  {
    extract($this->parsePath($name));

    if ($sub !== false) {
      $args = func_get_args();
      $filter = sy_get_param($args, 1);

      return $this->has($name) && $this->get($name)->has($sub);
    }

    return ($name == '.') || ($name == '..') || (isset($this->data[$name]));
  }

  /**
   * Parse $data into Config.
   *
   * @param mixed $data source data
   * @return Config
   */
  public static function parseFrom($data, Config $parent = null)
  {
    if ($data instanceof self && $data->up() === $parent)
      return $data;

    return new self($data, $parent);
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/data/IDictionary#reset($data, $except, $filter)
   */
  public function reset($data = null)
  {
    $args = func_get_args();
    $except = sy_get_param($args, 1);
    $filter = sy_get_param($args, 2);

    $this->data = array();

    $this->copyAll($data, $except, $filter);

    return $this;
  }

  /**
   *
   * @return Config
   */
  public function root()
  {
    return $this->up() ? $this->up()->root() : $this;
  }

  /**
   * Resolve references in the form {name}
   *
   * @param mixed $value
   * @return mixed
   */
  public function resolveReferences($value)
  {
    if (is_string($value)) {
      while (false !== ($i = strpos($value, '{')) && false !== ($f = strpos($value, '}', $i))) {
        $find = substr($value, $i, $f - $i + 1);
        $name = substr($value, $i + 1, $f - $i - 1);

        $replace = strpos($name, ':') !== 0 ? $this->root()->get($name) : $this->get(substr($name, 1));

        $value = str_replace($find, $replace, $value);
      }
    }

    return $value;
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/data/IDictionary#set($name, $value)
   */
  public function set($name, $value)
  {
    if (! is_array($this->data)) {
      $this->data = array(
        $this->env => array()
      );
    }

    extract($this->parsePath($name));

    if ($sub !== false) {
      if ($this->get($name) instanceof self) {
        $this->get($name)->set($sub, $value);
      }

      else {
        $child = self::parseFrom(array(
          $sub => $value
        ), $this);

        $this->set($name, $child);
      }
    }

    else {
      if ($value instanceof self) {
        $value = $value->getAll();
      }

      if (is_array($value)) {
        if ($this->get($name) instanceof self) {
          $this->get($name)->copyAll($value);
        }

        else {
          $this->data[$name] = self::parseFrom($value, $this);
        }
      }

      else {
        $this->data[$name] = $this->resolveReferences($value);
      }
    }

    return $this;
  }

  public function up()
  {
    return $this->parent;
  }

  public function __toString()
  {
    return '[object Config]';
  }

}

?>